<?php

namespace login\model;

require_once("common/model/UserDAL.php");
require_once("common/model/User.php");

class LoginModel {

	const minUserLength = 3;
	const minPasswordLength = 4;

	private static $sessionUsername = "USERNAME";
	private static $sessionPassword = "PASSWORD";
	private static $sessionUser = "sessionUser";
	private static $userAgent = "HTTP_USER_AGENT";
	
	/**
	 * @var \common\model\UserDAL
	 */
	private $UserDAL;

	public function __construct(\common\model\BaseDAL $baseDAL) {

		$this->UserDAL = new \common\model\UserDAL($baseDAL);
	}

	/**
	 * if a username is set in the seesion return true
	 * @return bool
	 */
	public function checkSession() {
		if (isset($_SESSION[self::$sessionUsername]) 
				  && isset($_SESSION[self::$sessionPassword])) {
			return true;
		}
	}

	/**
	 * Unset and destroy the session
	 * @return void
	 */
	public function logout() {
		$_SESSION = array();
    	session_destroy();
	}

	/**
	 * check if session is not stolen
	 * @return bool
	 */
	public function validateSession() {
		if ($_SESSION[self::$sessionUser] == $_SERVER[self::$userAgent]) {
			return true;
		}
	}

	/**
	 * set the time for cookies to expire
	 * @return int
	 */
	public function cookieExperation() {

		return time() + 360;
	}

	/**
	 * returns the current user in the session
	 * @return string
	 */
	public function getSessionUser() {
		if (isset($_SESSION[self::$sessionUsername])) {
			return $_SESSION[self::$sessionUsername];
		}
	} 

	/**
	 * set username and password in the session and save the user agent
	 * @param \common\model\User $user
	 */
	public function setSession(\common\model\User $user) {
		$_SESSION[self::$sessionUsername] = $user->username;
		$_SESSION[self::$sessionPassword] = $user->password;		
		$_SESSION[self::$sessionUser] = $_SERVER[self::$userAgent];
	}

	/**
	 * returns a hashed string
	 * @param  string $password
	 * @return string $password
	 */
	public function hashPassword($password) {

		return md5($password);
	}

	/**
	 * @param  User $user
	 * @return void
	 */
	public function login(\common\model\User $user) {
		$this->validateUser($user);
		$this->setSession($user);
	}

	/**
	 * @param \common\model\User $user
	 * @return void
	 */
	public function validateUser(\common\model\User $user) {
		//look for the user in the database
		$dbUser = $this->UserDAL->findUser($user);

		//if the username does not match any username in the database throw exception
		if ($user->username != $dbUser->username) {
			throw new \Exception("User doesn't exist");
		}
		//if the password does not match the given username throw exception
		if ($user->password != $dbUser->password) {
			throw new \Exception("Password does belong to user");
		}
	}
}